<?php
// $Id$

/**
 * Controller_Admin_Interface 控制器
 */
class Controller_Admin_Interface extends Controller_Abstract
{
	function actionCategory()
	{
		$typeid = intval($this->_context->modelid);
		$parentid = intval($this->_context->parentid);
		$jsoncallback = $this->_context->jsoncallback;
		$aout = Categorys::get_category_tree($typeid,'array',$parentid);
		if ($aout) {
			$tmp = '';
			foreach ($aout as $k => $v)
			{
				$tmp []= array($k,$v);
			}
			return json_encode($tmp);
		}
		return json_encode(array(array('0'=>"顶级分类")));
	}
	function actionUpload()
	{
		$allowExt = 'jpg,png,gif,bmp,swf';
		$upFolder = 'uploadfiles/tmp/';
		if($this->_context->isPOST())
		{
			$errorString  = '';
			# 图片上传
			$uploader = new Helper_Uploader();
			if ($uploader->filesCount()){
				$uploader = new Helper_Uploader();
				$upfile = $uploader->file('uploadfile');
				$extname = $upfile->extname();# 扩展名
				$old_name = $upfile->filename();
				if($upfile->isSuccessed()){
					if($upfile->isValid($allowExt)){
						$filename = md5($old_name.time()).'.'.$extname;
						$filepath = $upFolder.$filename;
						# 移动文件
						$upfile->move($filepath);
						if (!$upfile->isMoved()){
							$errorString = '图片上传失败!请检查服务器配置!';
						}else{
							$errorString = '图片上传成功!';
							$this->_view['filepath'] = $filepath;
						}
					}else{
						$errorString = '图片上传失败!图片格式不正确!';
					}
				}else{
					$errorString = '图片上传失败!请检查服务器配置!';
				}
			}
			unset($uploader);
			$this->_view['errorString'] = $errorString;
			$this->_viewname = 'uploadpost';
		}else{
			$this->_viewname = 'upload';
		}
	}

	function actionXlsUpload()
	{
		$allowExt = 'xls,csv,xlsx,bmp,swf';
		$upFolder = 'uploadfiles/tmp/';
		if($this->_context->isPOST())
		{
			$errorString  = '';
			# 图片上传
			var_dump($_FILES);
			$uploader = new Helper_Uploader();
			if ($uploader->filesCount()){
				$uploader = new Helper_Uploader();
				$upfile = $uploader->file('filedata');
				$extname = $upfile->extname();# 扩展名
				$old_name = $upfile->filename();
				if($upfile->isSuccessed()){
					if($upfile->isValid($allowExt)){
						$filename = md5($old_name.time()).'.'.$extname;
						$filepath = $upFolder.$filename;
						# 移动文件
						$upfile->move($filepath);
						if (!$upfile->isMoved()){
							$errorString = '上传失败!请检查服务器配置!';
						}else{
							$errorString = '上传成功!';
							$this->_view['filepath'] = $filepath;
						}
					}else{
						$errorString = '上传失败!格式不正确!';
					}
				}else{
					$errorString = '上传失败!请检查服务器配置!';
				}
			}
			unset($uploader);
			$this->_view['errorString'] = $errorString;
			$this->_viewname = 'uploadpost';
		}else{
			$this->_viewname = 'upload';
		}
	}
	/**
	 *
	 * 上传文件
	 */
	function actionUploadeditor()
	{
		header('Content-Type: text/html; charset=UTF-8');
		// 获取文件保存路径
		$attachDir = Q::ini('appini/xheditor/uploaddir');//上传路径数组
		$folder = trim($this->_context->get('folder'));
	    $folder = 'default';
		$attachDir = Q::ini('appini/xheditor/uploaddir/'.$folder);
		// 上传后回调
		$callback = trim($this->_context->get('callback'));
		$rate = doubleval($this->_context->rate);
		if ($callback)
		{
			if (method_exists($this,$callback))
			{
				// 回调函数存在
			}else{
				// 不存在回调函数
				return "{'err':'回调函数不存在,上传失败!','msg':'上传失败!'}";
			}
		}
		// 开始
		$inputName = 'filedata';//表单文件域name
		$dirType = Q::ini('appini/xheditor/savetype');//1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
		$maxAttachSize = Q::ini('appini/xheditor/maxsize');//最大上传大小，默认是2M
		if(intval($this->_context->maxkb))
		{
			$maxAttachSize = intval($this->_context->maxkb)*1024;
		}
		$upExt = Q::ini('appini/xheditor/allfileext');//上传扩展名
		$msgType = 2;//返回上传参数的格式：1，只返回url，2，返回参数数组
		$immediate = 1;//isset($_GET['immediate'])?$_GET['immediate']:0;//立即上传模式，仅为演示用
		ini_set('date.timezone','Asia/Shanghai');//时区

		$err = "";
		$msg = "''";
		$tempPath = $attachDir.'/'.date("YmdHis").mt_rand(10000,99999).'.tmp';
		$localName = '';

		if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){//HTML5上传
			file_put_contents($tempPath,file_get_contents("php://input"));
			$localName = $info[2];
		}else{
			//标准表单式上传
			$upfile = @$_FILES[$inputName];
			//var_dump($upfile);die;
			if(!isset($upfile)) $err = '文件域的name错误';
			elseif(!empty($upfile['error'])){
				switch($upfile['error'])
				{
					case '1':
						$err = '文件大小超过了php.ini定义的upload_max_filesize值';
						break;
					case '2':
						$err = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
						break;
					case '3':
						$err = '文件上传不完全';
						break;
					case '4':
						$err = '无文件上传';
						break;
					case '6':
						$err = '缺少临时文件夹';
						break;
					case '7':
						$err = '写文件失败';
						break;
					case '8':
						$err = '上传被其它扩展中断';
						break;
					case '999':
					default:
						$err = '无有效错误代码';
				}
			}
			
			elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$err = '无文件上传';
			else{
			    if(strpos($upfile['type'], 'image') !== false){
    				$aa=getimagesize($upfile['tmp_name']);
    				$weight=$aa["0"];////获取图片的宽
    				$height=$aa["1"];///获取图片的高
    				if($rate && ($weight/$height) <> $rate)
    				{
    						$err = '请保证图片的宽高比为:'.$rate;
    				}else{
    					move_uploaded_file($upfile['tmp_name'],$tempPath);
    					$localName = $upfile['name'];
    				}
			      }else{
			          move_uploaded_file($upfile['tmp_name'],$tempPath);
			          $localName = $upfile['name'];
			      }
				
			}
		}
		if($err == ''){
			$fileInfo = pathinfo($localName);
			$extension = $fileInfo['extension'];
			if(preg_match('/'.str_replace(',','|',$upExt).'/i',$extension))
			{
				$bytes = filesize($tempPath);
				if($bytes > $maxAttachSize)$err = '请不要上传大小超过'.$this->_formatBytes($maxAttachSize).'的文件';
				else
				{
					switch($dirType)
					{
						case 1: $attachSubDir = 'day_'.date('ymd'); break;
						case 2: $attachSubDir = 'month_'.date('ym'); break;
						case 3: $attachSubDir = 'ext_'.$extension; break;
					}
					$attachDir = $attachDir.'/'.$attachSubDir;
					if(!is_dir($attachDir))
					{
						@mkdir($attachDir, 0777);
						@fclose(fopen($attachDir.'/index.htm', 'w'));
					}
					PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
					$newFilename = date("YmdHis").mt_rand(1000,9999).'.'.$extension;
					$targetPath = $attachDir.'/'.$newFilename;

					rename($tempPath,$targetPath);
					@chmod($targetPath,0755);
					$targetPath = $this->_jsonString($targetPath);
					if($immediate == '1') $targetPath = '!'.$targetPath;
					if($msgType == 1) {
						$msg = "'$targetPath'";
					}else{
						$msg = "{'url':'".$targetPath."','localname':'".$this->_jsonString($localName)."','id':'1'}";//id参数固定不变，仅供演示，实际项目中可以是数据库ID	
					}
					// 回调函数
					if ($callback)
					{
						$this->$callback($this->_context, trim($targetPath,'!'));
					}
				}
			}
			else $err = '上传文件扩展名必需为：'.$upExt;

			Helper_Common::safeDelFile($tempPath);
		}

		return "{'err':'".$this->_jsonString($err)."','msg':".$msg."}";
	}

	/**
	 *
	 * 编辑器 远程图片拉取 上传文件
	 */
	function actionSaveremoteimg()
	{
		header('Content-Type: text/html; charset=UTF-8');
		$attachDir = Q::ini('appini/xheditor/uploaddir');//上传路径数组
		$folder = trim($this->_context->get('folder'));
		if (!isset($attachDir[$folder])) $folder = 'default';
		$attachDir = Q::ini('appini/xheditor/uploaddir/'.$folder);
		$dirType = Q::ini('appini/xheditor/savetype');//1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
		$maxAttachSize = 2097152;//最大上传大小，默认是2M
		$upExt = 'jpg,jpeg,gif,png';//上传扩展名
		ini_set('date.timezone','Asia/Shanghai');//时区

		$arrUrls = explode('|',$_POST['urls']);
		$urlCount = count($arrUrls);
		for($i=0 ; $i < $urlCount; $i++){
			$localUrl = $this->_saveRemoteImg($arrUrls[$i]);
			if($localUrl) $arrUrls[$i] = $localUrl;
		}
		echo implode('|',$arrUrls);exit;
	}
	function _jsonString($str)
	{
		return preg_replace("/([\\\\\/'])/",'\\\$1',$str);
	}
	function _formatBytes($bytes) {
		if($bytes >= 1073741824) {
			$bytes = round($bytes / 1073741824 * 100) / 100 . 'GB';
		} elseif($bytes >= 1048576) {
			$bytes = round($bytes / 1048576 * 100) / 100 . 'MB';
		} elseif($bytes >= 1024) {
			$bytes = round($bytes / 1024 * 100) / 100 . 'KB';
		} else {
			$bytes = $bytes . 'Bytes';
		}
		return $bytes;
	}
	//保存远程文件
	function _saveRemoteImg($sUrl){
		$upExt = Q::ini('appini/xheditor/allimgext');
		$maxAttachSize = Q::ini('appini/xheditor/maxsize');
		$reExt = '('.str_replace(',','|',$upExt).')';
		if(substr($sUrl,0,10) == 'data:image'){//base64编码的图片，可能出现在firefox粘贴，或者某些网站上，例如google图片
			if(!preg_match('/^data:image\/'.$reExt.'/i',$sUrl,$sExt)) return false;
			$sExt = $sExt[1];
			$imgContent = base64_decode(substr($sUrl,strpos($sUrl,'base64,')+7));
		}else{//url图片
			if(!preg_match('/\.'.$reExt.'$/i',$sUrl,$sExt))return false;
			$sExt=$sExt[1];
			$imgContent = $this->_getUrl($sUrl);
		}
		if(strlen($imgContent) > $maxAttachSize)return false;//文件体积超过最大限制
		$sLocalFile = $this->_getLocalPath($sExt);
		file_put_contents($sLocalFile,$imgContent);
		//检查mime是否为图片，需要php.ini中开启gd2扩展
		$fileinfo = getimagesize($sLocalFile);
		if(!$fileinfo||!preg_match("/image\/".$reExt."/i",$fileinfo['mime'])){
			Helper_Common::safeDelFile($sLocalFile);
			return false;
		}
		return $sLocalFile;
	}
	//抓URL数据
	function _getUrl($sUrl,$jumpNums=0){
		$arrUrl = parse_url(trim($sUrl));
		if(!$arrUrl)return false;
		$host = $arrUrl['host'];
		$port = isset($arrUrl['port'])?$arrUrl['port']:80;
		$path = $arrUrl['path'].(isset($arrUrl['query'])?"?".$arrUrl['query']:"");
		$fp = @fsockopen($host,$port,$errno, $errstr, 30);
		if(!$fp)return false;
		$output = "GET $path HTTP/1.0\r\nHost: $host\r\nReferer: $sUrl\r\nConnection: close\r\n\r\n";
		stream_set_timeout($fp, 60);
		@fputs($fp,$output);
		$Content = '';
		while(!feof($fp))
		{
			$buffer = fgets($fp, 4096);
			$info = stream_get_meta_data($fp);
			if($info['timed_out'])return false;
			$Content .= $buffer;
		}
		@fclose($fp);
		//global $jumpCount;//重定向
		if(preg_match("/^HTTP\/\d.\d (301|302)/is",$Content)&&$jumpNums<5)
		{
			if(preg_match("/Location:(.*?)\r\n/is",$Content,$murl))return $this->_getUrl($murl[1],$jumpNums+1);
		}
		if(!preg_match("/^HTTP\/\d.\d 200/is", $Content))return false;
		$Content = explode("\r\n\r\n",$Content,2);
		$Content = $Content[1];
		if($Content)return $Content;
		else return false;
	}
	//创建并返回本地文件路径
	function _getLocalPath($sExt){
		$dirType = Q::ini('appini/xheditor/savetype');
		$attachDir = Q::ini('appini/xheditor/uploaddir/default');
		switch($dirType)
		{
			case 1: $attachSubDir = 'day_'.date('ymd'); break;
			case 2: $attachSubDir = 'month_'.date('ym'); break;
			case 3: $attachSubDir = 'ext_'.$sExt; break;
		}
		$newAttachDir = $attachDir.'/'.$attachSubDir;
		if(!is_dir($newAttachDir))
		{
			@mkdir($newAttachDir, 0777);
			@fclose(fopen($newAttachDir.'/index.htm', 'w'));
		}
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		$newFilename = date("YmdHis").mt_rand(1000,9999).'.'.$sExt;
		$targetPath = $newAttachDir.'/'.$newFilename;
		return $targetPath;
	}
	/**
	 * 
	 * 更新游戏截图
	 */
	function _save_game_images($context,$url)
	{
		$gameid = trim($context->gameid);
		$game_extend = GameExtend::find('gameid = ?',$gameid)->setColumns('gameid,images')->getOne();
		if ($game_extend->id()) {
			$game_extend->changeProps(array('images'=>trim($game_extend->images,',') . ',' . str_replace('\/', '/', $url)));
			$game_extend->save();
		}
	}
	
	function actionsetnumPerPage()
	{
		$numPerPage = intval($this->_context->numPerPage);
		if($numPerPage>200)$numPerPage = 200;
		
		$_SESSION['numPerPage'] = $numPerPage;
	}

	 function actionuploadvideo(){
	 	$allowExt = 'mp4,mkv,avi';
		$upFolder = 'uploadfiles/tmp/';
		if($this->_context->isPOST())
		{
			$errorString  = '';
			# 视频上传
			var_dump($_FILES);
			$uploader = new Helper_Uploader();
			if ($uploader->filesCount()){
				$uploader = new Helper_Uploader();
				$upfile = $uploader->file('filedata');
				$extname = $upfile->extname();# 扩展名
				$old_name = $upfile->filename();
				if($upfile->isSuccessed()){
					if($upfile->isValid($allowExt)){
						$filename = md5($old_name.time()).'.'.$extname;
						$filepath = $upFolder.$filename;
						# 移动文件
						$upfile->move($filepath);
						if (!$upfile->isMoved()){
							$errorString = '上传失败!请检查服务器配置!';
						}else{
							$errorString = '上传成功!';
							//上传至阿里云
							$set = acct::find('id=?',1)->getOne();
							if(!$set->aliaccessid){
								$errorString = '上传失败!请设置阿里云accessid!';
							}
							if(!$set->aliaccesskey){
								$errorString = '上传失败!请设置阿里云accesskey!';
							}
							$al_upload = helper_voduploadsdk_vodupload::testUploadLocalVideo($set->aliaccessid,$set->aliaccesskey,$filepath);

							// $this->_view['filepath'] = $filepath;
						}
					}else{
						$errorString = '上传失败!格式不正确!';
					}
				}else{
					$errorString = '上传失败!请检查服务器配置!';
				}
				$msg = "{'url':'".$filepath."','localname':'".$this->_jsonString($filename)."','id':'1'}";//
			}
			unset($uploader);
			return "{'err':'".$this->_jsonString($errorString)."','msg':".$msg."}";
		}

	 }
}